#!/usr/bin/env python

import json
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import sys
import wave
import struct


if len(sys.argv) != 2:
    print "please input the feedback dump file"
    sys.exit(-1);

all_in0 = []
all_in1 = []
all_out0 = []
all_out1 = []

datas = json.load(open(sys.argv[1]))
for data in datas:
    #print 'loaded ', data
    if 'in0' not in data:
        continue
    in0 = data['in0']
    in1 = []
    if 'in1' in data:
        in1 = data['in1']
    else:
        in1 = [0] * len(in0)
    out0 = data['out0']
    out1 = []
    if 'out1' in data:
        out1 = data['out1']
    else:
        out1 = [0] * len(out1)
    all_in0 += in0
    all_in1 += in1
    all_out0 += out0
    all_out1 += out1
#    ests.append(data['est'])
#    dts.append(data['dt'])
#    dss.append(data['ds'])

# fin0 = wave.open('/tmp/in0.wav', 'w')
# fin1 = wave.open('/tmp/in1.wav', 'w')
# fout0 = wave.open('/tmp/out0.wav', 'w')
# fout1 = wave.open('/tmp/out1.wav', 'w')
#
# fin0.setparams((2, 2, 16000, 0, 'NONE', 'not compressed'))
# fin1.setparams((2, 2, 16000, 0, 'NONE', 'not compressed'))
# fout0.setparams((2, 2, 16000, 0, 'NONE', 'not compressed'))
# fout1.setparams((2, 2, 16000, 0, 'NONE', 'not compressed'))
#
# for i, v in enumerate(all_in0):
#     fin0.writeframes(struct.pack('h', v))
# for i, v in enumerate(all_in1):
#     fin1.writeframes(struct.pack('h', v))
# for i, v in enumerate(all_out0):
#     fout0.writeframes(struct.pack('h', v))
# for i, v in enumerate(all_out1):
#     fout1.writeframes(struct.pack('h', v))
#
# fin0.close()
# fin1.close()
# fout0.close()
# fout1.close()

hist_res = [500,150]

plt.figure(1)

ax1 = plt.subplot(4,1,1)
ax1.plot(all_in0, 'g-', label='in0')
ax2 = plt.subplot(4,1,2)
ax2.plot(all_in1, 'g-', label='in1')
ax3 = plt.subplot(4,1,3)
ax3.plot(all_out0, 'r-', label='out0')
ax4 = plt.subplot(4,1,4)
ax4.plot(all_out1, 'r-', label='out1')
ax1.legend()
ax2.legend()
ax3.legend()
ax4.legend()
ax1.grid(True)
ax2.grid(True)
ax3.grid(True)
ax4.grid(True)
plt.show()
